<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>动态Canvas位置调整示例</title>
    <style>
        body { display: flex; justify-content: center; margin-top: 20px; }
        #container { position: relative; width: 400px; height: 300px; border: 1px solid black; }
        canvas { position: absolute; width: 100%; height: 100%; }
        #backgroundCanvas { pointer-events: none;} /* 确保背景画布不接受任何鼠标事件 */
       
    </style>
</head>
<body>
    <div id="container"></div>
    <script>
        // 获取容器
        const container = document.getElementById('container');

        // 创建背景画布
        const backgroundCanvas = document.createElement('canvas');
        backgroundCanvas.id = 'backgroundCanvas';
        const bgCtx = backgroundCanvas.getContext('2d');

        // 创建文字画布
        const textCanvas = document.createElement('canvas');
        textCanvas.id = 'textCanvas';
        const textCtx = textCanvas.getContext('2d');

        // 将画布添加到容器中
        container.appendChild(backgroundCanvas);
        container.appendChild(textCanvas);

        // 设置画布大小和位置
        const dpr = window.devicePixelRatio || 1;
        const rect = container.getBoundingClientRect();
        backgroundCanvas.width = textCanvas.width = rect.width * dpr;
        backgroundCanvas.height = textCanvas.height = rect.height * dpr;
        // backgroundCanvas.style.left = container.offsetLeft + 'px';
        // backgroundCanvas.style.top = container.offsetTop + 'px';
        // textCanvas.style.left = container.offsetLeft + 'px';
        // textCanvas.style.top = container.offsetTop + 'px';
        bgCtx.scale(dpr, dpr);
        textCtx.scale(dpr, dpr);

        // 绘制背景辅助线
        const lineHeight = 18; // 行距
        const offset = 12; // 边缘偏移
        const numLines = Math.floor(rect.height / lineHeight);
        bgCtx.lineWidth = 0.5;
        for (let i = 0; i < numLines; i++) {
            const y = i * lineHeight + 0.5; // 在半像素位置绘制线条以增加清晰度
            bgCtx.beginPath();
            bgCtx.moveTo(offset, y);
            bgCtx.lineTo(rect.width - offset, y);
            bgCtx.stroke();
        }

        // 绘制文字层
        textCtx.font = "16px Arial";
        textCtx.fillText("这是文字层", 10, 50); // 在文字层上输出文字
    </script>
</body>
</html>
